package com.qf.chinatelcon.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class TimeStampFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 11;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        return context.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        //获取用户传递的时间戳
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String timestamp = request.getParameter("timestamp");//获取用户传递过来的时间戳
        long timeMillis = System.currentTimeMillis();//获取系统当前的时间
        System.err.println(timeMillis);
        long parseLong = Long.parseLong(timestamp);
        if (Math.abs(timeMillis - parseLong) > 60000) {
            context.setSendZuulResponse(false);
            context.setResponseBody("请求的时间超出范围差");
            context.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
        }
        return null;
    }
}
